package com.sharing.library.controller;

import com.sharing.library.entity.User;
import com.sharing.library.repository.UserRepository;
import com.zhx.framework.util.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhanghaixuan
 * @create 2018/3/17-下午1:48
 **/
@RestController
@RequestMapping("/user")
@Api(description="前端用户管理")
public class UserController {

    @Autowired
    private UserRepository userRepository;

    //注册
    @PostMapping("/regsiter")
    @ApiOperation(value="注册", notes="注册")
    public Result regsiter(@RequestBody User user){
        User byUsername = userRepository.findByUsername(user.getUsername());

        if(byUsername != null){
            return Result.Error(500,"用户已注册!");
        }


        User save = userRepository.save(user);

        return Result.OK("",save);
    }


    //登录
    @PostMapping("/login")
    @ApiOperation(value="登录", notes="登录")
    public Result login(@RequestParam String username,@RequestParam String pwd){
        User byUsername = userRepository.findByUsername(username);

        if(byUsername == null){
            return Result.Error(500,"账户名错误");
        }

        if(!byUsername.getPassword().equals(pwd)){
            return Result.Error(500,"密码错误");
        }

        return Result.OK("",byUsername);
    }


    //获取个人信息
    @PostMapping("/me")
    @ApiOperation(value="获取个人信息", notes="获取个人信息")
    public Result me(@RequestParam Long userId){
        User one = userRepository.findOne(userId);

        return Result.OK("",one);
    }

    //修改个人信息
    @PostMapping("/update")
    @ApiOperation(value="获取个人信息", notes="获取个人信息")
    public Result update(@RequestBody User user){
        User one = userRepository.save(user);

        return Result.OK("",one);
    }

}
